import {
	GetSw2ts, setConfSw2ts
} from './config';
import {
	api2format, dts2format, format2dts
} from './format';
import {
	GenerateAPI2dts, GenerateAxios2dts, GenerateInterface2dts, outputFileSync
} from './utils/index';
import logger from './utils/logger';

const path = require('path');

import createTransfer from './transfer/index';
import {
	readSchemaFromFile, readSchemaFromUrl
} from './utils/request';

export { createTransfer, readSchemaFromFile, readSchemaFromUrl, setConfSw2ts };

/**
 * 通过Swagger数据，生成 typescript 代码
 * @param data SwaggerSpec
 * @param aliasImport string
 * @returns
 */
export default function GenerateContext (config?: ConfigSw2ts) {
	if (config) setConfSw2ts(config);

	return (data: SwaggerSpec) => {
		return {
			paths: format2dts(GenerateAPI2dts(data)),
			definitions: format2dts(GenerateInterface2dts(data)),
		};
	};
}

const resolve = (input: string) => {
	return path.resolve(process.cwd(), input);
};

/**
 * 通过Swagger数据，生成 typescript 代码，并输出到文件
 * @param data SwaggerSpec
 * @param file string example: index.ts
 */
export async function Generate2API (data: SwaggerSpec, file?: string) {
	try {
		const sw2ts = GetSw2ts();
		const api = file ? api2format(file) : sw2ts.api;
		const dts = file ? dts2format(file) : sw2ts.dts;

		const context = GenerateContext()(data);

		if (context?.paths) {
			if (sw2ts.http) GenerateAxios2dts(sw2ts.http);
			outputFileSync(resolve(api), context.paths);
		}
		if (context?.definitions) {
			outputFileSync(resolve(dts), context.definitions);
		}

		logger.success(dts);
		logger.success(api);
		logger.success('√ API 生成完毕，已输出到上述文件');
	} catch (error) {
		logger.error(error);
	}
}
